<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 青 <99701759@qq.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace Home\Controller;
use Admin\Api\NewmemberApi;
use Admin\Api\OrdersPaycodeApi;
use Bbs\Api\BbsMemberApi;
use Shop\Api\BannersApi;
use Shop\Api\OrdersExpressApi;
use Shop\Api\ProductImageApi;
use Shop\Api\ProductMemberPriceApi;
use Think\Controller;

use Shop\Api\ProductApi;
use Shop\Api\ProductFaqApi;
use Shop\Api\ProductGroupApi;
use Shop\Api\ProductSkuApi;
use Ucenter\Api\UserLogApi;
use Weixin\Api\WxuserApi;
use Shop\Api\AddressApi;
use Shop\Api\ShoppingCartApi;
use Shop\Api\OrdersApi;
use Shop\Model\OrdersModel;
use Shop\Api\OrdersItemApi;
use Shop\Api\OrdersInfoViewApi;
use Shop\Api\OrderStatusApi;
use Shop\Api\OrderRefundApi;

class OrderController extends HomeController {
    /*
     * 所有订单分页查询
     * */
    public function index(){

        $this->display();
    }

    /*
     * 订单信息确认
     * */
    public function checkout(){

        session('pid',I('pid'));
        session('count',I('count'));
        session('sku_id',I('sku_id'));

        //收货地址的判断
        $addremap['uid'] = $this->userinfo['id'];

        //判断是否有可供选择的地址没有就需要新建
        $hasaddrres = apiCall(AddressApi::COUNT , array($addremap));
        if($hasaddrres['status']){
            $this->assign('addrecount',$hasaddrres['info']);
        }
        //判断是否进行地址选择如果选择了就用选择的 没有选择用默认的
        $addressmap['id'] = empty(I('addressid')) ?  $this->address : I('addressid');

        $selectres = apiCall(AddressApi::GET_INFO , array($addressmap));
        if($selectres['status']){

            $this->assign($selectres['info']);
            session('addressid',$selectres['info']['id']);//为的是在生成订单时获得相应的地址信息的方便
            $this->assign('addressid',$selectres['info']['id']);
        }


        $pid = !empty(I('pid')) ? I('pid') : session('pid');
        $count = !empty(I('count')) ? I('count') : session('count');
        $sku_id = !empty(I('sku_id')) ? I('sku_id'):session('sku_id');

        $this->assign('pid',$pid);
        $this->assign('count',$count);
        //判断一下商品数量
        $quantity = apiCall(ProductSkuApi::GET_INFO,array(array('sku_id' => $sku_id,'product_id' => $pid)));
        if($quantity['status']){
            if($quantity['info']['quantity'] < $count){
                $this->error('对不起库存不足');
            }
            $this->assign('skuid',$quantity['info']['id']);
            $this->assign('sku_desc',$quantity['info']['sku_desc']);
            $price['price'] = $quantity['info']['price']*$this->role['discount'];
            $price['totalprice'] = $quantity['info']['price']*$this->role['discount']*$count;
            $this->assign('price',$price);
            $jifen = $price['totalprice']*$this->role['integral_multiple'];
            $this->assign('jifen',$jifen);
        }
        $pinfores = apiCall(ProductApi::GET_INFO,array(array('id'=>$pid)));
        if($pinfores['status']){
            $this->assign('info',$pinfores['info']);
        }

        //获取商品图片
        $main_img_type = 6015;

        $result = apiCall(ProductImageApi::QUERY_NO_PAGING,array(array('pid' => $pid)));

        if(!$result['status']){
            return $result;
        }
        $main_img = "";
        foreach($result['info'] as $vo){
            if($vo['type'] == $main_img_type){
                $main_img = $vo['img_id'];
            }
        }
        $this->assign('img',$main_img);


        //查询收货地址
        $map=array(
            'uid'=> '1',
        );

        $result=apiCall(AddressApi::QUERY_NO_PAGING,array($map," id desc "));
        if($result['status']){
            if(empty($result['info'])){
                $result['info'] = array();
            }
            $this->assign('address',$result['info']);
        }
        //储值
        $this->assign('store_money',$this->newmember['store_money']);
        //积分
        $this->assign('points',$this->newmember['points']);
        //积分能抵多少钱
        $offset_money = floor($this->newmember['points']/100);
        $this->assign('offset_money',$offset_money);

        $this->display();
    }

    /*
     * 购物车下单的信息确认
     * */
    public function cart_checkout(){
        session('idnum',I('post.id'));
        //收货地址的判断
        $addremap['uid'] = $this->userinfo['id'];

        //判断是否有可供选择的地址没有就需要新建
        $hasaddrres = apiCall(AddressApi::COUNT , array($addremap));
        if($hasaddrres['status']){
            $this->assign('addrecount',$hasaddrres['info']);
        }
        //判断是否进行地址选择如果选择了就用选择的 没有选择用默认的

        $addressmap['id'] = empty(I('addressid')) ? $this->address : I('addressid');

        $selectres = apiCall(AddressApi::GET_INFO , array($addressmap));
        if($selectres['status']){
            $this->assign($selectres['info']);
            session('addressid',$selectres['info']['id']);//为的是在生成订单时获得相应的地址信息的方便
            $this->assign('addressid',$selectres['info']['id']);
        }
        //下面是商品详情
        $ids = !empty(I('post.id')) ? I('post.id') : session('idnum');
        $idarr = array();
        $idnumarr = array();
        foreach($ids as $co){
            $arr = explode('###',$co);
            $idarr[] = $arr['0'];
            $idnumarr[$arr['0']] = $arr['1'];
        }
        $str = implode(',',$idarr);
        $map['id'] = array('in',$str);
        $count = 0;
        $shopps = apiCall(ShoppingCartApi::QUERY_NO_PAGING,array($map));
        $totallprice = 0;
        if($shopps['status']){
            foreach($shopps['info'] as &$vo){
                $vo['price'] = ceil($vo['price']*$this->role['discount']);
                $totallprice = $totallprice + $vo['price']*$idnumarr[$vo['id']];
                $vo['count'] = $idnumarr[$vo['id']];
                $count = $count+$vo['count'];
                $vo['integral'] = $vo['price']*$this->role['integral_multiple'];
            }
            $this->assign('list',$shopps['info']);
        }

        //总共需要支付的金额
        $this->assign('totallprice',$totallprice);
        //储值
        $this->assign('store_money',$this->newmember['store_money']);
        //积分
        $this->assign('points',$this->newmember['points']);
        //积分能抵多少钱
        $offset_money = floor($this->newmember['points']/100);
        $this->assign('offset_money',$offset_money);

        $this->assign('count',$count);
        $this->display();
    }


    /*
     * 订单生成
     *
     * */
    public function produce_order(){
        session('pid',null);
        session('count',null);
        session('sku_id',null);
        session('idnum',null);
        //判断是否还有购买商品的权限
        $this->buy_power();

        //购买人的用户ID
        $uid = $this->userinfo['id'];
        $idskuidnum = I("idskuidnum","");
        $ids = array();
        $psku_id = array();
        $numarr = array();
        foreach($idskuidnum as $vo){
            $arr = explode('###',$vo);
            $ids[] = $arr['0'];
            $psku_id[] = $arr['1'];
            $numarr[$arr['0']] = $arr['2'];
        }

        $address_id = I('addressid'); //收货地址ID
        $note = I('note');

        //有购物车会出现多个物品一起提交

        $pay_type = 2; //支付类型 1:支付宝

        //1. 收货地址
        if(empty($address_id)){
            $this->error('收货地址缺失');
        }
        $result = apiCall(AddressApi::GET_INFO,array(array('id'=>$address_id)));
        if($result['status']){
            if(is_null($result['info'])){
                $this->error('收货地址缺失');
            }
        }else{
            $this->error('收货地址缺失');
        }

        $address = $result['info'];
        unset($address['id']);

        $entity = array();

        //合并收货地址
        $entity = array_merge($entity,$address);

        //2. 购物车信息
        $map = array(
            'id'=>array('in',$psku_id),
        );
        //1. 本商城生成的支付编号

        $result = apiCall(ProductSkuApi::QUERY_NO_PAGING,array($map));

        if($result['status']){

            $total = 0;
            $items = array();

            foreach($result['info'] as $vo){
                $total = $total+ceil($vo['price']*$this->role['discount'])*$numarr[$vo['product_id']];
                $map['id'] = $vo['product_id'];
                $productinfo = apiCall(ProductApi::GET_INFO,array($map));
                if($productinfo['status']){
                    $name = $productinfo['info']['name'];
                    $weight = $productinfo['info']['weight'];
                    $imgmap['pid'] = $vo['product_id'];
                    $imgmap['type'] = '6015';
                    $imgid = apiCall(ProductImageApi::GET_INFO,array($imgmap));

                    if($imgid['status']){
                        $img = $imgid['info']['img_id'];
                        $tmp = array(
                            'p_id' => $vo['product_id'],
                            'name' => $name,
                            'ori_price' => $vo['ori_price'],
                            'price' => $vo['price'],
                            'icon_url' => $img,
                            'count' => $numarr[$vo['product_id']],
                            'sku_id' => $vo['sku_id'],
                            'sku_desc' => $vo['sku_desc'],
                            'createtime' => time(),
                            'dt_origin_country' => $productinfo['info']['dt_origin_country'],
                            'weight' => $weight,
                            'taxrate' => '0',
                        );
                        $items[] = $tmp;
                    }
                }
            }

            $model = M();
            $model->startTrans();
            $flag = false;

            $balance = I('chuzhi','0');
            $points_mortgage = I('jifen','0');
            if($total < $balance){
                $balance = $total-$points_mortgage;
                //增加一个标志用于判断是否是全积分和储值
                $bflag = true;
            }


            $pay_score = '0';//表示使用了积分多少积分用于支付


            if($balance != 0 ||$points_mortgage != 0 ){
                $pointsmap =array(
                    'wx_id'=>$this->userinfo['id']
                );

                $pointsinfo = apiCall(NewmemberApi::GET_INFO,array($pointsmap));

                if($pointsinfo['status']){
                    if($pointsinfo['info']['points'] >= ($points_mortgage*100)){
                        $pay_score = $points_mortgage*100;//表示使用了积分多少积分用于支付
                    }

                    //判断储值是否大于顾客提交的

                    if($pointsinfo['info']['store_money'] < $balance){
                        $this->error('你的储值没有这么多');
                    }
                }

                //积分储值减少

                $pointsave['points'] = $pointsinfo['info']['points'] - $points_mortgage*100;

                $pointsave['store_money'] = $pointsinfo['info']['store_money'] - $balance;

                $pointsave['spend_money'] = $pointsinfo['info']['spend_money'] + $balance;
                $pointres = apiCall(NewmemberApi::SAVE,array($pointsmap,$pointsave));
                if(!$pointres['status']){
                    $flag = true;
                }

                //增加积分日志和储值日志
                if($balance !=0){
                    $addlogstoremoney = array(
                        'op_type'=>'98',
                        'number'=>-$balance,
                        'time' => time(),
                        'uid' => $this->userinfo['id'],
                        'note' => '购买商品',
                        'num_type'=>'1'
                    );
                    $addlogmoneyres = apiCall(UserLogApi::ADD,array($addlogstoremoney));
                    if(!$addlogmoneyres['status']){
                        $flag = true;
                    }
                }

                if($pay_score != 0){
                    $addlogpoints = array(
                        'op_type'=>'97',
                        'number'=>$pay_score,
                        'time' => time(),
                        'uid' => $this->userinfo['id'],
                        'note' => '购买商品抵现',
                        'num_type'=>'0'
                    );
                    $addlogpointsres = apiCall(UserLogApi::ADD,array($addlogpoints));
                    if(!$addlogpointsres['status']){
                        $flag = true;
                    }
                }

            }


            $order = array(
                'uid' => $entity['uid'],
                'order_code' => getOrderid($uid),
                'price' => $total,
                'post_price' => '0',
                'note' => $note,
                'pay_status'=>$bflag ? 1 : 0,
                'comment_status'=>0,
                'storeid' => '0',
                'idcode'=> '0',
                'discount_money'=> '0',
                'from'=> '1',
                'tax_amount'=> '0',
                'goods_amount'=> $total,
                'pay_type'=> $bflag ? 3 : 2,
                'pay_balance'=>$balance,
                'pay_score'=> $pay_score,
                'items' => $items
            );

            $entity = array_merge($entity,$order);

            $result = apiCall(OrdersApi::ADD_ORDER,array($entity));

            if($result['status']){
                //4. 添加到订单之后，就该删除购物车的数据
                $deleteres = $this->deleteFromShoppingCart($uid,$psku_id);
                $flag = $deleteres;
                //订单生成成功后库存的减少

                $numarr[$arr['0']] = $arr['2'];
                foreach($psku_id as $k => $vo){
                    $quantitymap = array(
                        'id' => $vo
                    );
                    $findquantity = apiCall(ProductSkuApi::GET_INFO,array($quantitymap));
                    if($findquantity['status']){
                        $saveq['quantity'] = $findquantity['info']['quantity']- $numarr["$ids[$k]"];
                        $saveres = apiCall(ProductSkuApi::SAVE,array($quantitymap,$saveq));
                        if(!$saveres['status']){
                            $flag = true;
                        }
                    }else{
                        $flag = true;
                    }
                    unset($saveres);
                }

            }else{
               $flag = false;
            }

            //星级会员将购买次数减去
            if($bflag){
                $buy_num = $this->newmember['buy_num'];
                $bsave['buy_num'] = $buy_num-1;
            }
            $bsave['get_stock_money'] = $this->newmember['get_stock_money']+$balance;
            $bmap['wx_id'] = $this->userinfo['id'];
            $bres = apiCall(NewmemberApi::SAVE,array($bmap,$bsave));
            if(!$bres['status']){
                $flag = true;
            }

            if($flag){
                $model->rollback();
                $this->error('对不起 订单生成出现问题');
            }else{

                $model->commit();
                if($bflag){
                    $this->success('下单成功',U('Order/wait_order',array('status'=>0)));
                    die();
                }
                $this->success('订单生成成功',U('TestPay/jsapi',array('order_code'=>$order['order_code'])));
            }

        }else{
            $this->error('对不起 订单生成出现问题');
        }

    }


    /**
     * 从购物车中删除
     * @author 老胖子-何必都 <hebiduhebi@126.com>
     * @param $uid
     * @param $cart_ids
     */
    private function deleteFromShoppingCart($uid,$cart_ids){
        $map = array(
            'uid'=>$uid,
            'psku_id'=>array('in',$cart_ids),
        );

        $result = apiCall(ShoppingCartApi::DELETE,array($map));
        if(!$result['status']){
            return true;
        }else{
            return false;
        }
    }


    private function getPayReturnInfo($pay_id,$uid,$total_price){
        $now = time();

        $code = 'T'.$now.'U'.$uid.'P'.$pay_id;
        $name = '订单'.$code;
        $desc = $name;
        //保留2位
        $total_price = round($total_price,2);
        $info = array(
            'code'=>$code,
            'name'=>$name,
            'desc'=>$desc,
            //@author 老胖子-何必都 <hebiduhebi@126.com>
            //转换成字符串，否则IOS端解析成数字类型时精度会有问题，比如74.10 被解析成74.09999999999999,从而导致APP端验证失败!
            'total_price'=>strval($total_price)
        );

        $encode = urlencode($code.$name.$desc.$total_price);
        $encode = md5(strtolower($encode));

        $info['key'] = pay_encrypt_md5($encode);
        $info['show_url'] = C('SITE_URL');

        return $info;
    }

    /**
     * 待支付订单分页查询
     */
    public function wait_order(){

        if(IS_GET){

            $uid = $this->userinfo['id'];
            $curpage = I('curpage',1);
            $pagesize = I('pagesize',10);
            $status = I('status');//待支付的订单
            $this->assign('status',$status);
            $curpage = intval($curpage);
            $pagesize = intval($pagesize);

            if($curpage < 1){
                $curpage = 1;
            }
            if($pagesize > 30){
                $pagesize = 30;
            }
            if($pagesize <= 0){
                $pagesize = 10;
            }

            $map=array(
                'uid'=>$uid,
            );

            if(!empty($status)){
                $map = array_merge($map,$this->getQueryStatus($status));
            }

            $page = array(
                'curpage'=>$curpage,
                'size'=>$pagesize
            );

            $order = "updatetime desc";

            $result = apiCall(OrdersApi::QUERY,array($map,$page,$order));
            if($result['status']){
                $orderList = $result['info']['list'];
                if(is_null($orderList)){
                    $this->display();
                    die();
                }

            }else{
                $this->error('查询出错了');
            }

            if($status == 3 ||$status == 0){
                $express = apiCall(OrdersExpressApi::QUERY_NO_PAGING);
                if($express['status']){
                    $this->assign('express',$express['info']);
                }
            }
            //查询orders_item
            $mapItem = $this->getMapFromResult($orderList);

            $result = apiCall(OrdersItemApi::QUERY_NO_PAGING,array($mapItem));

            if($result['status']){

                //计算总商品数
                $list =  $this->combine($orderList,$result['info']);
                $return = array('list'=>$list);
                $return['curpage'] = $curpage;
                $return['pagesize'] = $pagesize;

                foreach($return['list'] as &$vo){
                    foreach($vo['_items'] as &$item){
                        $vo['count'] = $vo['count'] + $item['count'];
                    }
                }

                $this->assign('list',$return['list']);
                $this->display();
            }else{
                $this->error('订单查询出错了');
            }

        }

    }

    /**
     * 将此处查询状态
     * 转换为订单状态或支付状态
     * @param $status
     * @return array
     */
    private function getQueryStatus($status){
        /*
            status = 0 //全部状态,

            status = 1 //待付款

            status = 2 //待发货

            status = 3 //待收货

            status = 4 //已收货

            status = 5 //退款/售后
            */

        $map = array();
        switch($status){
            case 0:
                break;
            case 1:
                $map['pay_status'] = OrdersModel::ORDER_TOBE_PAID;
                $map['order_status'] = OrdersModel::ORDER_TOBE_CONFIRMED;
                break;
            case 2:
                $map['pay_status'] = OrdersModel::ORDER_PAID;
                $map['order_status'] = array('in',array(OrdersModel::ORDER_TOBE_SHIPPED,OrdersModel::ORDER_TOBE_CONFIRMED));
                break;
            case 3:

                $map['order_status'] = OrdersModel::ORDER_SHIPPED;
                break;
            case 4:
                $map['order_status'] = OrdersModel::ORDER_RECEIPT_OF_GOODS;
                break;
            case 5:
                $map['cs_status'] = array('in',array(OrdersModel::CS_PENDING,OrdersModel::CS_PROCESSED));
                break;
            default:
                break;
        }
        return $map;
    }


    private function getMapFromResult(&$list){

        $newList = array();

        $mapItem = array();

        foreach($list as $vo){
            array_push($mapItem,$vo['order_code']);
            $newList[$vo['order_code']] = $vo;
            $newList[$vo['order_code']]['_items'] = array();
        }
        $list = $newList;
        return array('order_code'=>array('in',$mapItem));
    }


    /**
     * Convert
     * @param $order_list
     * @return mixed
     */
    private function combine($orderList,$itemList){
        foreach($itemList as $vo){
            $order = &$orderList[$vo['order_code']];
            $vo['img_url'] = getImageUrl($vo['img']);
            unset($vo['img']);
            if(!empty($order)){
                array_push($order['_items'],$vo);
            }
        }

        return $orderList;
    }

    /*
     * 订单详情
     * */
    public function detail2(){
        $id=I('id'); //订单ID

        $map=array(
            'id'=>$id,
        );
        $result=apiCall(OrdersInfoViewApi::GET_INFO,array($map));

        if($result['status']){

            $order=$result['info'];

            if(is_null($order)){
                $this->error("获取失败,没有此订单!");
            }

            $order['store_logo_url'] = getImageUrl($order['store_logo']);

            $map=array(
                'order_code'=>$order['order_code'],
            );
            $result=apiCall(OrdersItemApi::QUERY_NO_PAGING,array($map));
            if($result['status']){
                $order['items'] = $result['info'];

                $order['items'] = $this->convertDetail($result['info']);

            }else {
                $this->error("查询中发生错误，请联系相关人员");
            }
            $all_count = 0;
            foreach($order['items'] as &$vo){
                $vo['price'] = $vo['price']*$this->role['discount'];
                $all_count = $all_count+$vo['count'];
            }
            $this->assign('all_count',$all_count);
            $this->assign($order);

            $wxpressmap['order_code'] = $order['order_code'];
            $express = apiCall(OrdersExpressApi::GET_INFO,array($wxpressmap));
            if($express['status']){
                $this->assign('express',$express['info']);
            }

            $this->display();
        }else{
            $this->error("查询中发生错误，请联系相关人员");
        }
    }

    /*
     * 订单详情
     * */
    public function detail(){

        $id=I('id'); //订单ID

        $map=array(
            'id'=>$id,
        );
        $result=apiCall(OrdersInfoViewApi::GET_INFO,array($map));

        if($result['status']){

            $order=$result['info'];

            if(is_null($order)){
                $this->error("获取失败,没有此订单!");
            }

            $order['store_logo_url'] = getImageUrl($order['store_logo']);

            $map=array(
                'order_code'=>$order['order_code'],
            );
            $result=apiCall(OrdersItemApi::QUERY_NO_PAGING,array($map));
            if($result['status']){
                $order['items'] = $result['info'];

                $order['items'] = $this->convertDetail($result['info']);

            }else {
                $this->error("查询中发生错误，请联系相关人员");
            }

            $this->assign($order);

            $this->display();
        }else{
            $this->error("查询中发生错误，请联系相关人员");
        }

    }




    /**
     * Convert
     * @param $order_list
     * @return mixed
     */
    private function convertDetail($list){
        foreach($list as &$vo) {
            $vo['img_url'] = getImageUrl($vo['img']);
        }
        return $list;
    }

    /*
     * 取消订单
     * */
    public function cancel(){
        $uid = $this->userinfo['id'];

        $order_code = I('order_code',0);
        $findmap = array(
            'order_code' => $order_code,
            'uid' => $uid
        );

        $ores = apiCall(OrdersApi::GET_INFO,array($findmap));
        if($ores['status']){
            if($ores['info']['pay_status'] == 1){
                $this->error('订单已经支付成功无法取消');
            }elseif($ores['info']['pay_status'] == 0){
                $modal = M();
                $modal->startTrans();
                $flag = false;
                $save = array('order_status'=>8);

                $sres = apiCall(OrdersApi::SAVE,array($findmap,$save));

                if(!$sres['status']){
                    $flag = true;
                }

                //将支付的储值回退和获得消费股份累加钱数回退 和消费累计金额回退
                $money = $ores['info']['pay_balance'];
                if($money > 0){
                    $store_money = bcadd($money,$this->newmember['store_money'],2);
                    $nmap['wx_id'] = $uid;
                    $nsave['store_money'] = $store_money;
                    $total_money = bcsub($this->newmember['get_stock_money'],$money,2);
                    $nsave['get_stock_money'] = $total_money;

                    $nsave['spend_money'] = bcsub($this->newmember['spend_money'],$money,2);
                    $nres = apiCall(NewmemberApi::SAVE,array($nmap,$nsave));
                    if(!$nres['status']){
                       $flag = true;
                    }
                }




                //将支付的积分回退
                $points = $ores['info']['pay_score'];
                if($points > 0){
                    $spoints = bcadd($points,$this->newmember['points'],2);
                    $nmap['wx_id'] = $uid;
                    $nsave['points'] = $spoints;
                    $pres = apiCall(NewmemberApi::SAVE,array($nmap,$nsave));
                    if(!$pres['status']){
                        $flag = true;
                    }
                }

                if($flag){
                    $modal->rollback();
                    $this->error('订单取消失败');
                }else{
                    $modal->commit();
                    $this->success('订单取消成功');
                }

            }
        }else{
            $this->error('订单取消失败');
        }

    }

    /*
     * 重新发起支付
     * */
    public function rePay(){
        $this->display();
    }

    /*
     * 确认收货
     * */
    public function confirm_receipt(){
        if(!empty(I('order_code'))) {
            $map['order_code'] = I('order_code');
            $save['order_status'] = 5;//表示已经收货
            $result = apiCall(OrdersApi::SAVE, array($map, $save));
            if ($result['status']) {
                echo true;
            } else {
                echo false;
            }
        }else{
            echo false;
        }

    }



    /*
     * 申请售后
     * */
    public function afterSale(){
        $order_code = I('order_code');
        $this->assign('order_code',$order_code);
        $this->display();
    }

    /*
     * 申请换货
     * */
    public function barter(){
        $order_code = I('order_code');
        $info = $this->package_detail('',$order_code);

        if($info){
            $this->assign('all_count',$info['all_count']);
            $this->assign('order',$info['order']);
        }else{
            $this->error('订单信息获取失败');
        }

        $this->display();
    }

    /*
     *仅退款
     * */
    public function refund(){
        $order_code = I('order_code');
        $info = $this->package_detail('',$order_code);

        if($info){
            $this->assign('all_count',$info['all_count']);
            $this->assign('order',$info['order']);
        }else{
            $this->error('订单信息获取失败');
        }

        $this->display();

    }

    /*
     * 退货退款
     * */
    public function barter_refund(){
        $order_code = I('order_code');
        $info = $this->package_detail('',$order_code);

        if($info){
            $this->assign('all_count',$info['all_count']);
            $this->assign('order',$info['order']);
        }else{
            $this->error('订单信息获取失败');
        }

        $this->display();
    }


    /*
     *
     * 申请售后ajax
     * */
    public function afterSale_post(){
        if(IS_POST){

            $uid        = I("uid",0);
            $order_code = I('order_code','');
            $reason     = I('reason','无');
            $rtype      = I('refund_type','');
            $is_get     = I('goods_get','');
            $note       = I('note','无');
            $money      = I('refund_money',0);
            $rtype = intval($rtype);
            if(!in_array($rtype,[1,2,3])) $this->error('售后类型错误');
            $is_get = intval($is_get);
            if(!in_array($is_get,[1,2])) $this->error('售后类型错误');
            $map = [
                'order_code'=>$order_code
            ];
            $r = apiCall(OrderRefundApi::GET_INFO,[$map]);
            if(!$r['status']) $this->error('申请售后失败!');
            $refund_info = $r['info'];

            $now = time();
            $entity = ['create_time'=>$now,'reason'=>$reason,'valid_status'=>0,'reply_msg'=>'','reply_time'=>0,'order_code'=>$order_code,'refund_type'=>$rtype,'goods_get'=>$is_get,'note'=>$note,'refund_money'=>$money];
            if(empty($refund_info)){
                // trace(" ==== ");
                // trace($entity);
                $r = apiCall(OrderRefundApi::ADD,[$entity]);
            }else{

                if(0 == $refund_info['valid_status']){
                    //待审核，无法再次申请售后，直接返回提示文字（正在审核中）
                    $this->error('您已经申请过售后，请耐心等待客服处理！');
                }else{
                    //重新发起售后
                    $r = apiCall(OrderRefundApi::SAVE,array($map,$entity));
                }
            }

            if(!$r['status']) $this->error('申请售后失败!信息:'.$r['info']);

            //修改订单的售后状态
            $r = apiCall(OrderRefundApi::CHANGE_SERVICE_STATUS,array($order_code,2));
            if($r['status']){
                $this->success('申请售后成功，等待客服反馈!');
            }else{
                $this->error('订单发生未知错误!');
            }

        }else{
            $this->error('只支持post请求');
        }
    }


    /*
     * 订单查询的封装
     * */
    public function package_detail($id,$order_code){
        $id = $id; //订单ID
        $order_code = $order_code;

        if(!empty($id)){
            $map=array(
                'id'=>$id,
            );
        }

        if(!empty($order_code)){
            $map=array(
                'order_code' => $order_code,
            );
        }
        $result = apiCall(OrdersInfoViewApi::GET_INFO,array($map));

        if($result['status']){

            $order=$result['info'];

            if(is_null($order)){
                $this->error("获取失败,没有此订单!");
            }

            $order['store_logo_url'] = getImageUrl($order['store_logo']);

            $map=array(
                'order_code'=>$order['order_code'],
            );
            $result=apiCall(OrdersItemApi::QUERY_NO_PAGING,array($map));
            if($result['status']){
                $order['items'] = $result['info'];

                $order['items'] = $this->convertDetail($result['info']);
            }else {
                $this->error("查询中发生错误，请联系相关人员");
            }
            $all_count = 0;
            foreach($order['items'] as &$vo){
                $vo['price'] = $vo['price']*$this->role['discount'];
                $all_count = $all_count+$vo['count'];
            }

            $res = array(
                'all_count' => $all_count,
                'order' => $order
            );

            return $res;

        }else{
            return false;
        }
    }


    /*
     * 是否有购买所有商品的次数及权限的判断
     * */
    public function buy_power(){
        $vip = $this->newmember['vip'];
        $grade = $this->newmember['role_grade'];
        if($vip == 1&&$grade == 1){
            $num = $this->newmember['buy_num'];
            if($num == 0){
                $this->error('不好意思您已经没有购买商品的机会了');
            }
        }
    }


}